import { login } from '@/api/api'
import { apiSysPower } from '@/api/system'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = () => {
  return {
    token: getToken(),
    name: '',
    phone: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    roles: [],
    roleName: '',
  }
}

const mutations = {
  SET_ROLE_NAME: (state, roleName) => {
    state.roleName = roleName
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password })
        .then((response) => {
          const { result } = response
          localStorage.setItem('feijiu_user_name', result.name)
          localStorage.setItem('feijiu_user_id', result.id)
          localStorage.setItem('feijiu_user_uid', result.uid)
          localStorage.setItem('feijiu_user_info', JSON.stringify(result))
          setToken(result.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取菜单权限
  getMenu({ commit, state }) {
    return new Promise((resolve, reject) => {
      apiSysPower()
        .then((res) => {
          const { data } = res
          localStorage.setItem('feijiu_user_menu', JSON.stringify(data))
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      localStorage.removeItem('feijiu_user_menu')
      localStorage.removeItem('feijiu_user_name')
      localStorage.removeItem('feijiu_user_id')
      localStorage.removeItem('feijiu_user_uid')
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      dispatch('permission/setAsyncRoutes', null, { root: true })
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      // commit('SET_TOKEN', '')
      // commit('SET_ROLES', [])
      removeToken() // must remove  token  first
      resolve()
    })
  },
  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async (resolve) => {
      const token = role + '-token'

      // commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
